import 'package:cached_network_image/cached_network_image.dart';
import 'package:factoryside/api/api.dart';
import 'package:factoryside/utils/FadeRoute.dart';
import 'package:factoryside/utils/request_util.dart';
import 'package:factoryside/utils/utils.dart';
import 'package:factoryside/widget/page_photo_view.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class OrderRecordPage extends StatefulWidget{

  //从上一个页面传过来的工单号
  int orderId;

  OrderRecordPage(this.orderId);

  @override
  State<StatefulWidget> createState() {
    return OrderRecordPageState();
  }
}

class OrderRecordPageState extends State<OrderRecordPage>{

  List recordList;

  @override
  void initState() {
    super.initState();
    RequestUtil.post(Api.getOrderRecordByGrid,{'orderId':widget.orderId}).then((value) {
      setState(() {
        recordList=value['Data']['data'];
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar:buildAppBar('工单跟踪',null,context),
      //未获取到数据就居中显示加载图标
      body: recordList != null ?  buildBody(context) : showLoading(),
    );
  }

  Widget buildBody(BuildContext context){
    return Column(
      children: <Widget>[
        buildListView(context),
      ],
    );
  }

  Widget buildListView(BuildContext context){
    return Expanded(
      child: Container(
        color: Colors.white,
        child: ListView.builder(
          //想设置item为固定高度可以设置这个，不过文本过长就显示不全了
//            itemExtent: 100,
            itemCount: recordList == null ? 0 : recordList.length,
            itemBuilder: (BuildContext context, int position){
              return buildListViewItem(context, position);
            }
        ),
      ),
    );
  }

  Widget buildListViewItem(BuildContext context, int position){
    List imgList=recordList[position]['LeavemessageimgList'];
    List<String> urllist=List();
    if (imgList!=null) {
      imgList.forEach((element) {
            urllist.add(element['Url']);
          });
    }
    if(recordList.length != 0){
      return Container(
        color: Colors.white,
        padding: EdgeInsets.only(left: 20, right: 10),
        child: IntrinsicHeight(child: Row(
          children: [
            //这个Container描绘左侧的线和圆点
            Container(
              margin: EdgeInsets.only(left: 10),
              width: 20,
              child: Column(
                //中心对齐，
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Expanded(
                      flex: 1,
                      child: Container(
                        //第一个item圆点上方的线就不显示了
                        width: position == 0 ? 0 : 1,
                        color: Colors.grey.shade300,
                      )
                  ),
                  //第一个item显示稍大一点的绿色圆点
                  position == 0 ? Stack(
                    //圆心对齐（也就是中心对齐）
                    alignment: Alignment.center,
                    children: <Widget>[
                      //为了实现类似阴影的圆点
                      Container(
                        height: 20,
                        width: 20,
                        decoration: BoxDecoration(
                          color: Colors.red.shade200,
                          borderRadius: BorderRadius.all(Radius.circular(10)),
                        ),
                      ),
                      Container(
                        height: 14,
                        width: 14,
                        decoration: BoxDecoration(
                          color: Colors.red,
                          borderRadius: BorderRadius.all(Radius.circular(7)),
                        ),
                      ),
                    ],
                  ) : Container(
                    height: 10,
                    width: 10,
                    decoration: BoxDecoration(
                      color: Colors.grey.shade300,
                      borderRadius: BorderRadius.all(Radius.circular(5)),
                    ),
                  ),
                  Expanded(
                      flex: 1,
                      child: Container(
                        width: position == recordList.length-1 ? 0 : 1,
                        color: Colors.grey.shade300,
                      )
                  ),
                ],
              ),
            ),
            Expanded(
              child: Padding(
                padding: EdgeInsets.fromLTRB(20, 20, 20, 20),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      recordList[position]['MegType']==0?'【留言】${recordList[position]['Content']}':recordList[position]['Content'],
                      style: TextStyle(
                        fontSize: 15,
                        //第一个item字体颜色为绿色+稍微加粗
                        color: position == 0 ? Colors.red : Colors.black,
                        fontWeight: position == 0 ? FontWeight.w600 : null,
                      ),
                    ),
                    Wrap(
                      children: urllist
                          .asMap()
                          .keys
                          .map((index) => buildGestureDetector_img(
                          index, urllist))
                          .toList(),
                    ),
                    SizedBox(height: 5,),
                    Text(recordList[position]['CreateDate'].replaceAll('T', ' '),
                      style: TextStyle(
                        fontSize: 15,
                        //第一个item字体颜色为绿色+稍微加粗
                        color: position == 0 ? Colors.red : Colors.grey,
                        fontWeight: position == 0 ? FontWeight.w600 : null,
                      ),
                    ),
                    SizedBox(height: 5,),
                    Text((recordList[position]['UserName']),
                      style: TextStyle(
                        fontSize: 15,
                        //第一个item字体颜色为绿色+稍微加粗
                        color: position == 0 ? Colors.red : Colors.black,
                        fontWeight: position == 0 ? FontWeight.w600 : FontWeight.bold,
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),),
      );
    }else{
      return Container();
    }
  }

  Widget showLoading(){
    return Center(
      child: CircularProgressIndicator(),
    );
  }

  GestureDetector buildGestureDetector_img(int index, List<String> urls) {
    return GestureDetector(
      child: Container(
        margin: EdgeInsets.only(right: 5),
        child: CachedNetworkImage(
          imageUrl:urls[index],
          width: 40,
          height: 40,
          fit: BoxFit.fill,
        ),
      ),
      onTap: () {
        //FadeRoute是自定义的切换过度动画（渐隐渐现） 如果不需要 可以使用默认的MaterialPageRoute
        Navigator.of(context).push(FadeRoute(
            page: PhotoViewGalleryScreen(
              images: urls, //传入图片list
              index: index, //传入当前点击的图片的index
              heroTag: '', //传入当前点击的图片的hero tag （可选）
            )));
      },
    );
  }

  //把int类型的状态转成字符串，具体对应请看阿里云API购买页面，本博最后的图也会有
  String statusConvert(int status){
    String returnStatus;
    switch(status) {
      case -1: { returnStatus = "待查询"; }
      break;
      case 0: { returnStatus = "查询异常"; }
      break;
      case 1: { returnStatus = "暂无记录"; }
      break;
      case 2: { returnStatus = "在途中"; }
      break;
      case 3: { returnStatus = "派送中"; }
      break;
      case 4: { returnStatus = "已签收"; }
      break;
      case 5: { returnStatus = "用户拒签"; }
      break;
      case 6: { returnStatus = "疑难件"; }
      break;
      case 7: { returnStatus = "无效单"; }
      break;
      case 8: { returnStatus = "超时单"; }
      break;
      case 9: { returnStatus = "签收失败"; }
      break;
      case 10: { returnStatus = "退回"; }
      break;
      default: { returnStatus = "未知状态"; }
      break;
    }
    return returnStatus;
  }
}
